from collections import OrderedDict
from goods.models import GoodsChannel


def get_categories():
    """获取商城商品分类菜单"""
    # 创建有序列表对象
    categories = OrderedDict()
    # 查询数据库，根据组号和组内顺序排序获取到频道数据
    channels = GoodsChannel.objects.order_by('group_id', 'sequence')
    # print(channels)
    # 遍历查询结果，把同组的数据添加到有序字典中
    for channel in channels:
        # 获取当前组
        group_id = channel.group_id
        # 判断当前组是否在有序字典中
        if group_id not in categories:
            # 如果没有就添加字典数据
            categories[group_id] = {'channels': [], 'sub_cats': []}
        # print(categories)
        # 获取顶级分类数据
        cat1 = channel.category
        # print(cat1)
        # 把每个顶级分类数据追加到对应的分组
        categories[group_id]['channels'].append({
            'id': cat1.id,
            'name': cat1.name,
            'url': channel.url
        })
        # print(categories)
        # 查询所有二级分类数据，遍历
        for cat2 in cat1.goodscategory_set.all():
            cat2.sub_cats = []
            # 查询三级分类
            for cat3 in cat2.goodscategory_set.all():
                cat2.sub_cats.append(cat3)
            categories[group_id]['sub_cats'].append(cat2)
    return categories
